
from libs.base.model import BaseModel
from libs.tools.widget import Common


class UserListModel(BaseModel):
    """获取用户列表"""
    def __init__(self, handler):
        super(UserListModel, self).__init__(handler)
        self.handler = handler
        self.data = {}

    async def fetch_user_list(self, opts):

        """
        获取用户列表
        """
        list_sql, count_sql, values = self._parse_list_sql(opts)
        data_list = await self._fetch_list_data(list_sql, values)
        total_count = await self._total_count(count_sql, values, data_list, opts)

        data = Common.list_model_data(data_list, total_count, opts)
        return self.set_res_info(0, data=data)

    def _parse_list_sql(self, opts):
        """sql查询"""
        sql_base = """
            SELECT user_id, account,name, email, phone_number, 
                create_by, create_time 
             FROM auth_user
             WHERE {where}
             {order} {limit}
        """
        queries, values = [], []
        opts['key_allow'] = [
            ['name', '{key}', 'like'],
            ['user_id', '{key}'],
            ['account', '{key}'],
            ['email', '{key}'],
            ['phone_number', '{key}'],
            ['create_by', '{key}'],
            ['data_status=1', '{key}', 'raw']
        ]
        opts['order_allow'] = [['user_id', '{key}'], ['account', '{key}']]
        infos = Common.parse_where(queries, values, opts)

        list_sql = sql_base.format(**infos)
        count_sql = Common.parse_count_sql(infos['where'], sql_base)

        return list_sql, count_sql, values

    async def _fetch_list_data(self, list_sql, values):
        """异步请求"""
        await self.db.execute(list_sql, values)
        data_list = self.db.fetchall()
        await self.get_users(data_list, ["create_by"])
        return data_list


class UserInfoModel(BaseModel):
    """操作用户"""
    def __init__(self, handler, user_id=None):
        super(UserInfoModel, self).__init__(handler)
        self.handler = handler
        self.user_id = user_id
        self.data = {}

    async def fetch_info(self, opts):
        """
        获取用户的基本信息
        """
        # 校验id是否存在
        flag = await self._check_data_exist()
        if flag != 0:
            return self.set_res_info(flag)
        # fetch
        selects = [
            "user_id", "account", "password", "name", "email",
            "phone_number", "create_by", "create_time", "data_status"
        ]
        await self.db.select("auth_user", selects, {"user_id": self.user_id})
        info = self.db.fetchone()
        await self.get_users(info, ["create_by"])
        return self.set_res_info(0, data=info)

    async def _check_data_exist(self):
        # 校验数据ID是否存在
        wheres = {'user_id': self.user_id, 'data_status': 1}
        await self.db.select('auth_user', 'Count', wheres)
        count = self.db.fetchone().get('Count')
        # 不存在，返回状态码4005；存在 返回0
        return 4005 if count != 1 else 0

    async def insert_info(self, opts):
        """新增用户"""

        # 校验是否重复

        flag = await self._check_data_unique(opts)

        if flag != 0:
            return self.set_res_info(flag)
        # 添加数据
        self.fill_create_info(opts)

        user_id = await self.db.insert('auth_user', opts)

        if not self.db.errors:
            await self.db.commit()
        return self.set_res_info(0,data={"user_id": user_id})

    async def _check_data_unique(self,opts):
        """校验主字段是否重复"""
        wheres = {
            "user_id!": self.user_id or 0,
            "name": opts['name'],
            'data_status': 1

        }
        await self.db.select('auth_user', 'Count', wheres)
        count = self.db.fetchone().get('Count')
        #  重复， 返回状态4008；不重复，返回0
        return 4008 if count > 0 else 0

    async def delete_info(self):
        """
        软删除用户
        """
        # 校验id是否存在
        flag = await self._check_data_exist()
        if flag != 0:
            return self.set_res_info(flag)
        # delete
        wheres = {"user_id": self.user_id, "data_status": 1}
        await self.db.update("store_info", {"data_status": -1}, wheres)
        if not self.db.errors:
            await self.db.commit()
        return self.set_res_info(0)

    async def update_info(self, opts):
        """修改用户的基本信息"""

        #  检验user_id 是否存在
        flag = await self._check_data_exist()
        if flag != 0:
            return self.set_res_info(flag)
        # 检验是否重复
        flag = await self._check_data_unique(opts)
        if flag != 0:
            return self.set_res_info(flag)
        # update
        wheres = {"user_id": self.user_id, "data_status": 1}
        await self.db.update('auth_user', opts, wheres)
        if not self.db.errors:
            await self.db.commit()
        return self.set_res_info(0)


class UserModel(BaseModel):
    """用户模型权限类"""
    def __init__(self, handler):
        super(UserModel, self).__init__(handler)
        self.handler = handler
        self.data = {}

    async def get_user_info(self):
        """
        获取用户基本信息和权限
        """
        data = {
            "user_id": self.user["user_id"],
            "account": self.user["account"],
            "name": self.user["name"],
            "email": self.user["email"],
            "phone_number": self.user["phone_number"],
            "create_time": self.user["create_time"],
            "permissions": self.user["permissions"]
        }
        return self.set_res_info(0, data=data)



